package cn.com.kh;

import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

/**
 * @projectName: ngsapitask-sw
 * @package: cn.com.kh
 * @className: KHSWUtil
 * @author: LiJT
 * @description: TODO 深圳水务客制化工具类
 * @date: 2022-10-25 16:57
 * @version: 1.0
 */

public class KHSWUtil {
    private static final Log log = LogFactory.getLog(KHSWUtil.class);

    /**
     * @param eliteBean:EliteBean
     * @param Documentout_Guid:短信Guid
     * @param mobiles:手机
     * @param content:短信内容
     * @param loginName:账号
     * @param businessType:业务类型
     * @param userMsgId:业务流水号
     * @param extInfo:扩展号
     * @return JSONObject
     * @author LiJT
     * @description TODO 发送不带批次信息的短信
     * @date 2022-10-31 23:26
     */
    public static JSONObject sendSWSms(EliteBean eliteBean, String Documentout_Guid, String mobiles, String content, String loginName, String businessType, String userMsgId, String extInfo) {
        return sendSWSms(eliteBean, Documentout_Guid, mobiles, content, loginName, businessType, userMsgId, extInfo, "");
    }

    /**
     * @param eliteBean:EliteBean
     * @param Documentout_Guid:短信Guid
     * @param mobiles:手机
     * @param content:短信内容
     * @param loginName:账号
     * @param businessType:业务类型
     * @param userMsgId:业务流水号
     * @param extInfo:扩展号
     * @param batchName:批次名称
     * @return JSONObject
     * @author LiJT
     * @description TODO 发送带批次信息的短信
     * @date 2022-10-31 23:27
     */
    public static JSONObject sendSWSms(EliteBean eliteBean, String Documentout_Guid, String mobiles, String content, String loginName, String businessType, String userMsgId, String extInfo, String batchName) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("sendSWSms 参数-Documentout_Guid:" + Documentout_Guid + " mobiles:" + mobiles + " content:" + content + " loginName:" + loginName);

        try {
            // 获取发送所需要的Token
            loginName = KHUtil.isNull(loginName) ? "SMS_JT" : loginName;
            String doSendURL = KHDBConfig.getAPIURL(eliteBean, "UnSMSURL_Send_" + loginName);
            String doSendID = KHDBConfig.getParamConfig(eliteBean, "UnSMS_ID_" + loginName);
            String doSendPWD = KHDBConfig.getParamConfig(eliteBean, "UnSMS_PWD_" + loginName);

            String timeStamp = String.valueOf(System.currentTimeMillis());
            String signInfo = doSendID + doSendPWD + timeStamp;

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json;charset=utf-8");
            headParams.put("accept", "application/json");
            headParams.put("timestamp", timeStamp);
            headParams.put("sign", Util.getSHA256Str(signInfo));

            // 发送对象
            JSONObject postJson = new JSONObject();
            postJson.put("loginName", doSendID);
            postJson.put("mobiles", mobiles);
            postJson.put("content", loginName.equals("SMS_BJ") ? content.replace("【深圳水务集团】", "【深圳布吉水司】") : content);
            postJson.put("businessType", businessType);

            // 非必填，拓展号
            if (!KHUtil.isNull(extInfo)) {
                postJson.put("ext", extInfo);
            }
            // 非必填，客户业务流水号，报告时返回，长度不能超过20
            if (!KHUtil.isNull(userMsgId)) {
                postJson.put("userMsgId", userMsgId);
            }
            // 非必填，批次名称，长度不能超过50个字
            if (!KHUtil.isNull(batchName)) {
                postJson.put("batchName", batchName);
            }

            log.debug("调用SW短信发送报文：" + postJson.toString());

            String resultInfo = Util.doHttpPostUseHead(doSendURL, postJson.toString(), "UTF-8", 30000, 0, headParams);
            log.debug("调用SW短信发送返回：" + resultInfo);

            JSONObject resultJson = JSONObject.fromObject(resultInfo);
            String code = resultJson.getString("code");

            resultSendSms.put("code", resultJson.getString("code"));
            resultSendSms.put("msg", resultJson.getString("msg"));

            if (code.equals("0")) {
                resultSendSms.put("msgId", resultJson.getString("msgId"));
            }

        } catch (Exception e1) {
            log.error("调用SW短信发送异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", "调用SW短信发送异常");

        }

        log.debug("调用SW短信发送结果：" + resultSendSms.toString());

        return resultSendSms;
    }

    /**
     * @param eliteBean:
     * @param loginName:
     * @return JSONObject
     * @author LiJT
     * @description TODO 获取指定账号的短信
     * @date 2022-10-31 23:27
     */
    public static JSONObject resultSWSms(EliteBean eliteBean, String loginName) {
        return resultSWSms(eliteBean, loginName, "");
    }

    /**
     * @param eliteBean:
     * @param loginName:
     * @param extInfo:
     * @return JSONObject
     * @author LiJT
     * @description TODO 获取指定账号+拓展号的短信
     * @date 2022-10-31 23:27
     */
    public static JSONObject resultSWSms(EliteBean eliteBean, String loginName, String extInfo) {
        JSONObject resultSendSms = new JSONObject();
        long startTime = System.currentTimeMillis();

        log.debug("短信平台短信结果 参数-loginName:" + loginName + " extInfo:" + extInfo);
        int resArrNum = 0;

        JSONObject postJson = new JSONObject();
        JSONObject resultJson = new JSONObject();
        try {
            // 获取所需要配置
            loginName = KHUtil.isNull(loginName) ? "CRMAPI" : loginName;
            String doSendURL = KHDBConfig.getAPIURL(eliteBean, "UnSMSURL_Result_" + loginName);
            String doSendID = KHDBConfig.getParamConfig(eliteBean, "UnSMS_ID_" + loginName);
            String doSendPWD = KHDBConfig.getParamConfig(eliteBean, "UnSMS_PWD_" + loginName);

            String timeStamp = String.valueOf(System.currentTimeMillis());
            String signInfo = doSendID + doSendPWD + timeStamp;

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json;charset=utf-8");
            headParams.put("accept", "application/json");
            headParams.put("timestamp", timeStamp);
            headParams.put("sign", Util.getSHA256Str(signInfo));

            // 发送对象
            postJson.put("loginName", doSendID);

            // 非必填，客户业务流水号，报告时返回，长度不能超过20
            if (!KHUtil.isNull(extInfo)) {
                postJson.put("ext", extInfo);
            }
            log.debug("短信平台短信结果(非催缴)-调用SW短信结果报文：" + postJson.toString());

            String resultInfo = Util.doHttpPostUseHead(doSendURL, postJson.toString(), "UTF-8", 30000, 0, headParams);
            log.debug("短信平台短信结果(非催缴)-调用SW短信结果返回：" + resultInfo);

            resultJson = JSONObject.fromObject(resultInfo);
            String code = resultJson.getString("code");

            resultSendSms.put("code", resultJson.getString("code"));
            resultSendSms.put("msg", resultJson.getString("msg"));

            if (code.equals("0")) {
                resArrNum = resultJson.getJSONArray("reportList").size();
                resultSendSms.put("data", resultJson.getJSONArray("reportList"));
            }

        } catch (Exception e1) {
            log.error("短信平台短信结果(非催缴)-调用SW短信结果异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", "调用SW短信结果异常");

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "获取指定账号的短信", "apiDataExchange", postJson.toString(), resultJson.toString(), String.valueOf(System.currentTimeMillis() - startTime), "入参新信息:" + loginName + "/" + extInfo + " Num:" + resArrNum);
        }

        log.debug("短信平台短信结果(非催缴)-调用SW短信结果返回结果：" + resultSendSms.toString());

        return resultSendSms;
    }

    /**
     * @param eliteBean: 数据源Bean
     * @param sms_Guid:  短信批次ID
     * @return boolean
     * @author LiJT
     * @description TODO 深圳水务批量短信免打扰时间检查
     * @date 2022-11-09 00:51
     */
    public static boolean isSendSMSTime(EliteBean eliteBean, String sms_Guid) {
        boolean isSendTime = true;
        try {

            String StopTimeFlag = KHDBConfig.getParamConfig(eliteBean, "BatchSMS_StopTimeFlag");
            log.debug("深圳水务批量短信免打扰时间检查-是否启用检查参数配置BatchSMS_StopTimeFlag:" + StopTimeFlag);
            if (!KHUtil.isNull(StopTimeFlag) && StopTimeFlag.equals("1")) {
                JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

                String checkTimeSQL = "Select Count(*) As Plan_No_Sendtime,\n" + "       (Select Count(*)\n" + "          From Sys_Parameter_Config\n" + "         Where Status = 1\n" + "           And Parameter_Id = 'BatchSMS_StopSendTime'\n" + "           And Charindex(',' + Right('0' + Datename(Hh, Getdate()), 2) + ',', ',' + Parameter_Value + ',') > 0) As Sys_No_Sendtime\n" + "  From Sms_No_Intime\n" + " Where Plan_Guid = ?\n" + "   And Starttime < Getdate()\n" + "   And Getdate() < Endtime";
                List<Map<String, Object>> checkTimeList = jt.queryForList(checkTimeSQL, sms_Guid);

                int ListNum = checkTimeList.size();
                log.debug("深圳水务批量短信免打扰时间检查-规则结果ListNum:" + ListNum + " 规则结果:" + checkTimeList);
                if (ListNum > 0) {
                    int Plan_No_Sendtime = Integer.parseInt(checkTimeList.get(0).get("Plan_No_Sendtime").toString());
                    int Sys_No_Sendtime = Integer.parseInt(checkTimeList.get(0).get("Sys_No_Sendtime").toString());
                    if (Plan_No_Sendtime > 0 || Sys_No_Sendtime > 0) {
                        isSendTime = false;
                    }
                    log.debug("深圳水务批量短信免打扰时间检查-当前为系统禁止发送时间isSendTime:" + isSendTime);
                } else {
                    log.debug("深圳水务批量短信免打扰时间检查-未查询到配置-跳过检查SQL:" + checkTimeSQL);
                }
            } else {
                log.debug("深圳水务批量短信免打扰时间检查-配置暂不启用");
            }
        } catch (Exception e) {
            log.warn("深圳水务批量短信免打扰时间检查-规则结果异常:" + e.getMessage());

        }
        return isSendTime;
    }
}
